package com.rajaev.dtu.tractor.infrastructure.helper;

import com.rajaev.dtu.tractor.domain.entity.UserInfo;
import com.rajaev.dtu.tractor.domain.service.UserInfoDomain;
import com.rajaev.dtu.tractor.infrastructure.base.common.Constants;
import com.rajaev.dtu.tractor.infrastructure.base.errors.BusinessException;
import com.rajaev.dtu.tractor.interfaces.dto.LoginUserWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static com.rajaev.dtu.tractor.infrastructure.base.common.Constants.Authorization;

@Component
public class UserSecurityUtil {

    @Autowired
    UserInfoDomain userService;

    @Autowired
    RedisTemplate redisTemplate;

    public LoginUserWrapper getLoginUser(HttpServletRequest request) throws BusinessException {

        if (!SpringEnvHelper.isProd() && StringUtils.isEmpty(request.getHeader(Authorization))) {
            return getDevUser(request);
        }

        String loginName = (String) redisTemplate.opsForValue().get(Constants.cacheTokenPrefix + request.getHeader(Authorization));
        UserInfo userInfo = userService.getUserByLoginName(loginName);
        LoginUserWrapper loginUserWarpper = new LoginUserWrapper();
        loginUserWarpper.setUserInfo(userInfo);
        loginUserWarpper.setToken(request.getHeader(Authorization));
        return loginUserWarpper;

    }

    LoginUserWrapper getDevUser(HttpServletRequest request) throws BusinessException {
        UserInfo userPo = userService.getUserByLoginName("superman");
        LoginUserWrapper loginUserWarpper = new LoginUserWrapper();
        loginUserWarpper.setUserInfo(userPo);
        loginUserWarpper.setToken(request.getHeader(Authorization));
        return loginUserWarpper;
    }
}
